package org.biz.modules.service.impl;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import org.apache.commons.lang.StringUtils;
import org.biz.config.RedisCache;
import org.biz.exception.BussinessLogicException;
import org.biz.modules.entity.VerifyCode;
import org.biz.modules.mapper.SysUserMapper;
import org.biz.modules.mapper.VerifyCodeMapper;
import org.biz.modules.service.ShortMsgService;
import org.biz.util.RedisUtil;
import org.biz.util.ResponseEnum;
import org.biz.util.ShortMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service
@Transactional(readOnly = true)
public class ShortMessageServiceImpl implements ShortMsgService {

    @Value("${aliyun.acs.templateCode:}")
    private String templateCode;
    @Value("${aliyun.acs.templateCodeLogin}")
    private String templateCodeLogin;

    @Autowired
    private SysUserMapper userMapper;
    @Qualifier("getIAcsClient")
    @Autowired
    private IAcsClient acsClient;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private RedisCache redisCache;
    @Autowired
    private VerifyCodeMapper verifyCodeMapper;

    private Logger logger;

    {
        logger = LoggerFactory.getLogger(ShortMessageServiceImpl.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SendSmsResponse sendMessage(String phone, String type, String outId) throws BussinessLogicException {
        SendSmsRequest request = null;
        String template = "";
        switch (type) {
            case "register":
                template = templateCodeLogin;
                request = makeSendSmsRequest(phone, template, outId);
                break;
            case "findback":
                template = templateCode;
                request = makeSendSmsRequest(phone, template, outId);
                break;
            default:
                break;
        }
        if (request == null) {
            throw new BussinessLogicException("未确定短信模板类型！");
        }
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        Long code = generateRandomCode();
        dealSendMessage(phone, type, code);
        request.setTemplateParam("{\"code\":\"" + code +"\"}");
        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
            verifyCodeMapper.insert(new VerifyCode(sendSmsResponse, phone, code, template));
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if(sendSmsResponse != null && sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            return sendSmsResponse;
        }
        throw new BussinessLogicException(ResponseEnum.SHORT_MSG_SEND_ERROR);
    }

    @Override
    public String verify(String phone, String type, Long code) throws BussinessLogicException {
        String key = null;
        switch (type) {
            case "register":
                verify(phone, code, ShortMessage.REGISTER_MESSAGE);
                return "验证成功";
            case "findback":
                verify(phone, code, ShortMessage.FINDBACK_MESSAGE);
                return "验证成功";
            default:
                break;
        }
        return null;
    }

    private void verify(String phone, Long code, String findbackMessage) throws BussinessLogicException {
        String key;
        int correctCode;
        key = findbackMessage + phone;
        if (!redisUtil.hasKey(key)) {
            throw new BussinessLogicException(ResponseEnum.SHORT_MSG_MIS_MATCH);
        }
        correctCode = (int) redisUtil.get(key);
        if (correctCode != code) {
            throw new BussinessLogicException(ResponseEnum.SHORT_MSG_MIS_MATCH);
        }
        redisUtil.del(key);
    }

    private void dealSendMessage(String phone, String type, Long code) throws BussinessLogicException {
        String key = null;
        switch (type) {
            case "register":
                dealSendMessage(phone, code, ShortMessage.REGISTER_MESSAGE, ShortMessage.REGISTER_MESSAGE_EXPIREDTIME);
                break;
            case "findback":
                dealSendMessage(phone, code, ShortMessage.FINDBACK_MESSAGE, ShortMessage.FINDBACK_MESSAGE_EXPIREDTIME);
                break;
            default:
                break;
        }
    }

    private void dealSendMessage(String phone, Long code, String registerMessage, int registerMessageExpiredtime) throws BussinessLogicException {
        String key;
        Long expire;
        key = registerMessage + phone;
        if (StringUtils.isBlank(key)) {
            throw new BussinessLogicException("生成的 key 无效");
        }
        if (redisUtil == null) {
            throw new BussinessLogicException("缓存无效");
        }
        boolean hasKey = redisUtil.hasKey(key);
        if (hasKey) {
            expire = redisUtil.getExpire(key);
            logger.info(">>>>>>>>>>expire:"+expire);
            if (expire != null && registerMessageExpiredtime - expire < 60) {
                throw new BussinessLogicException(ResponseEnum.SHORT_MSG_SEND_FREQUENTLY_ERROR);
            }
        }
        logger.info(">>>>>>>>>>key:"+key);
        redisUtil.set(key, code, registerMessageExpiredtime);
    }


    private SendSmsRequest makeSendSmsRequest(String phone, String templateCode, String outId) {
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setSysMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("美中互健");
//        request.setSignName("南京美中互健信息科技");
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(templateCode);
        //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId(outId);
        return request;
    }

    /**
     * 随机获得6位验证码
     * @return
     */
    public Long generateRandomCode() {
        return Math.round(Math.random()*899999 + 100000);
    }

}
